//
// Created by hjie on 23-5-3.
//

#include "connection.h"
#include "channel.h"
#include "data_buffer.h"
#include "loop_event.hpp"

Connection::Connection(LoopEvent *loop, int socket, WriteAbleCallback && w_func, ReadAbleCallback && r_func, ErrorCallback && e_func)
{
    m_loop_event = loop;
    m_socket  = new TcpSocket(socket);

    Channel * channel = nullptr;
    channel = new Channel(loop, socket,
                            std::forward<WriteAbleCallback>(w_func),
                            std::forward<ReadAbleCallback>(r_func),
                            std::forward<ErrorCallback>(e_func));

    m_connection_channel = std::shared_ptr<Channel>(channel);
    m_data_buffer = new DataBuffer(socket);
}

Connection::~Connection()
{
    if (m_data_buffer)
    {
        delete m_data_buffer;
        m_data_buffer = nullptr;
    }
    if (m_socket)
    {
        delete m_socket;
        m_socket = nullptr;
    }
}

void Connection::RegisterChannel(int event_type)
{
    m_connection_channel->AddEvent(event_type);
}

int64_t Connection::ChannelId()
{
    return m_connection_channel->GetChannelId();
}

std::size_t Connection::SendData(const std::string & data)
{
    return send(m_socket->GetSocketFd(),data.c_str(), data.size(), 0);
}

std::size_t Connection::SendData(const uint8_t *data, std::size_t size)
{
    return send(m_socket->GetSocketFd(), data, size, 0);
}

void Connection::CloseConnection()
{
    if (m_connection_channel)
    {
        m_connection_channel->RemoveEvent();
        m_connection_channel = nullptr;
    }
}

void Connection::RemoveBufferData(int size)
{
    if (m_data_buffer)
    {
        m_data_buffer->RemoveData(size);
    }
}
